#include "rpcbalancer.h"
#include <lua.hpp>
using namespace yhaida;
int main(int argc, char *argv[])
{
  lua_State *L = luaL_newstate();
  luaopen_base(L);
  int err = luaL_dofile(L, "../config.lua");
  if (err)
  {
    abort();
  }
  LOG_INFO << "pid = " << getpid();
  std::vector<std::string> Addresses;
  lua_getglobal(L, "InetAddress");
  int n = luaL_len(L, 1); // luaL_len可以获得table的元素个数
  for (int i = 1; i <= n; ++i)
  {
    lua_pushnumber(L, i); //往栈里面压入i
    lua_gettable(L, -2);  //读取table[i]，table位于-2的位置。
                          // lua_rawget(L, -2);  //lua_gettable也可以用lua_rawget来替换
    Addresses.push_back(lua_tostring(L, -1));
    lua_pop(L, 1);
  }
  lua_pop(L, -1);
  lua_getglobal(L, "server_port");
  lua_getglobal(L, "server_numberThread");
  int server_port = lua_tonumber(L, -2);
  int server_numberThread = lua_tonumber(L, -1);
  lua_pop(L, -1);

  std::vector<InetAddress> backends;
  for (size_t i = 0; i < Addresses.size(); ++i)
  {
    std::string hostport = Addresses[i];
    size_t colon = hostport.find(':');
    if (colon != std::string::npos)
    {
      std::string ip = hostport.substr(0, colon);
      uint16_t port = static_cast<uint16_t>(atoi(hostport.c_str() + colon + 1));
      backends.push_back(InetAddress(ip, port));
    }
    else
    {
      fprintf(stderr, "invalid backend address %s\n", argv[i]);
      return 1;
    }
  }

  InetAddress listenAddr(server_port);

  EventLoop loop;
  Balancer balancer(&loop, listenAddr, backends);
  balancer.setThreadNum(server_numberThread);
  balancer.start();
  loop.loop();

  google::protobuf::ShutdownProtobufLibrary();
}